﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;

namespace CurrencyReferenceDAL
{
    public class CurrencyManager
    {
        public CurrencyManager(string url)
        {
            _list = listCurrenciesFromXml(url);
        }
        private List<Currency> listCurrenciesFromXml(string url)
        {
            var list = new List<Currency>();
            var nfiEzb = new NumberFormatInfo { NumberDecimalSeparator = "." };

            var xdoc = XDocument.Load(url);

            if (xdoc.Root != null)
            {
                list = (from nd in xdoc.Root.Descendants()
                        where nd.Name.LocalName == "Cube" && nd.Attributes().Count() == 2
                        select new Currency
                        {
                            CurrencySymbol = nd.Attribute("currency").Value,
                            RateAgainstEuro = Convert.ToDouble(nd.Attribute("rate").Value, nfiEzb)
                        }).ToList();
            }

            return list;
        }

        private List<Currency> _list;

        public List<Currency> Currencies
        {
            get { return _list; }
            set
            {
                _list = value;
            }
        } 
    }
}